<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          :data="list"
          border
          :default-sort="{prop:'timeOfEntry',order:'ascending'}"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column sortable label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" />  返回的数据中没有用户的状态 -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push('/detail')">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmployees(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2,3,5,10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addEmployees v-if="showDialog" @close="offClose" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getEmployees, delEmployees } from '@/api/employees'
// 枚举文件
import EmployeesEnum from '@/constant/employees'
// 导入子组件
import addEmployees from '@/views/employees/empDialog.vue'
// arr.reduce(('累计和','数组中的元素','索引号') => {},'默认值')
const hireType = EmployeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    addEmployees
  },
  data() {
    return {
      showDialog: false, // 控制对话框的显示和隐藏
      page: 1, // 页码值
      size: 5, // 每页显示的条数
      list: [], // 存储员工列表的信息
      total: 0 // 页面显示多少的数据
    }
  },

  mounted() {

  },
  created() {
    this.loadEmployess()
  },
  methods: {
    formData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 取出一个数据对象
      const one = list[0]
      // 判断one是否有值，如果没有直接终止程序
      if (!one) {
        //   list中没有数据
        return
      }
      console.log(Object.keys(one))
      // 使用对象生成需要的header数据
      const header = Object.keys(one).map(enKey => {
        return map[enKey]
      })
      console.log(header)
      // 生成data数据
      const data = list.map(item => {
        const key = item.formOfEmployment // key:1 || 2   ===> 正式 || 非正式
        // hireType = {1:'正式',2:'非正式'}
        item['formOfEmployment'] = hireType[key] || '未知'
        return Object.values(item)
      })

      return { header, data }
    },
    // 导入功能的关键代码
    async handleDownload() {
      const res = await getEmployees(this.page, this.size)
      console.log('导出请求', res)
      const { data, header } = this.formData(res.data.rows)
      console.log('导出数据', data, header)

      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: header,
          data: data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    // 删除员工列表按钮
    delEmployees(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployees(id)
        console.log('删除员工', res)
        // 删除页面最后一条数据自动页码值减一  判断
        if (this.list.length === 1) {
          this.page--
          // 页码值最小必须是1
          if (this.page <= 0) {
            this.page = 1
          }
        }
        // 重新渲染页面
        this.loadEmployess()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    // 子传父 关闭对话框
    offClose() {
      // 关闭对话框
      this.showDialog = false
      // 计算出最大页码值,实现添加员工自动定位到当前页面
      this.total++
      this.page = Math.ceil(this.total / this.size)
    },
    // 员工正式非正式的按钮
    formOfEmploymentFormat(data) {
      // 将传入的1||2 转化为正式||非正式
      // return EmployeesEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    },
    // 新增员工按钮
    // hAdd() {
    //   this.showDialog = true
    // },
    // 分页器的方法
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      // 重新渲染页面
      this.loadEmployess()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      // 重新渲染页面
      this.loadEmployess()
    },
    // 获取员工列表信息
    async loadEmployess() {
      try {
        const res = await getEmployees(this.page, this.size)
        console.log('res', res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
